package com.gupt.reggie.common;/*
@author name
@data 2023/4/18-17:20
*/

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLIntegrityConstraintViolationException;

//捕获(拦截哪些类抛出的异常  annotations(注解
@ControllerAdvice(annotations = {RestController.class, Controller.class})
//最终返回json数据
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException exception){
            log.info(exception.getMessage());

            if(exception.getMessage().contains("Duplicate entry")){
                String[] msg = exception.getMessage().split(" ");  //切割字符串变成数组
                String error = msg[2] + " 已存在";
                return R.error(error);
            }
            return R.error("系统错误，请重试");
    }

    @ExceptionHandler(CustomException.class)
    public R<String> exceptionHandler(CustomException ex){

        log.info(ex.getMessage());
        return R.error(ex.getMessage());//获取异常信息，返回给页面
    }
}
